const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Receipt.findAll({ include: ["Client", "Project", "Contract"] })
    .then((receipts) => res.send(receipts))
    .catch((err) => {
      res.send(err);
    });
});

router.get("/:id", verify, (req, res) => {
  db.Receipt.findAll({
    where: {
      id: req.params.id,
    },
  })
    .then((receipt) => {
      res.send(receipt);
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/add", verify, (req, res) => {
  const receipt = req.body;
  console.log(receipt);
  db.Receipt.create(receipt)
    .then((receipt) => {
      res.send(receipt);
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/delete", verify, (req, res) => {
  db.Receipt.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ deleted: n });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  db.Receipt.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ updated: n });
    })
    .catch((err) => {
      res.send(err);
    });
});
module.exports = router;
